package com.wn.ticket.web.backstage;

import com.wn.ticket.common.JwtUtils;
import com.wn.ticket.common.ResponseEntity;
import com.wn.ticket.entity.Admin;
import com.wn.ticket.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wuqingting
 * @date 2022/8/31
 */
@RestController
@RequestMapping("/backstage/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

//    @RequestMapping("/login")
//    public ResponseEntity login(@RequestBody Admin admin){
//        Admin admin1 = adminService.login(admin);
//        if (admin1!=null){
//            return ResponseEntity.success;
//        }
//
//        return ResponseEntity.fail;
//    }

    @PreAuthorize("hasAnyAuthority('super')")
    @RequestMapping("/add")
    public ResponseEntity add(@RequestBody Admin admin){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        admin.setPassword(encoder.encode(admin.getPassword()));//将密码加密
        adminService.add(admin);

        return ResponseEntity.success;
    }

    @Autowired
    private JwtUtils jwtUtils;
    @RequestMapping("/get")
    public ResponseEntity get(HttpServletRequest request){
        String token = request.getHeader("token");
        String account = (String) jwtUtils.getInfo(token, "account");

        return new ResponseEntity(account);
    }

    @RequestMapping("/getById/{id}")
    public ResponseEntity get(@PathVariable int id){
        Admin admin = adminService.getById(id);

        return new ResponseEntity(admin);
    }

    @PreAuthorize("hasAnyAuthority('super')")
    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody Admin admin){
        if (admin.getPassword()!=null&&admin.getPassword()!=""){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            admin.setPassword(encoder.encode(admin.getPassword()));
        }
        adminService.update(admin);
        return ResponseEntity.success;
    }

    @RequestMapping("/getAll")
    public ResponseEntity<Admin>getAll(){
        List<Admin> adminList=adminService.getAll();
        return new ResponseEntity("200","ok",adminList);
    }
}
